//
//  SYHomeViewController.m
//  SanYiTeaching
//
//  Created by 郑浩然 on 2020/6/25.
//  Copyright © 2020 SanYi. All rights reserved.
//

#import "SYHomeViewController.h"
#import "HPLeftTopView.h"
#import "HPClassView.h"
#import "HPOtherView.h"
#import "HPOtherRightView.h"
#import "HPFuDaoView.h"
#import "CalendarView.h"
#import "MainNavigationController.h"
#import "LoginViewController.h"
#import "CJClassSelectedView.h"
#import "HPSelectedClassView.h"
#import "SYRequestAPI+HomePage.h"
#import "HomePageLunBoTuModel.h"
#import "TeacherClassListModel.h"
#import "HomeCourseModel.h"
//师训信息
#import "HomeShiXunModel.h"
//在线辅导信息
#import "HomeOnlinTrainModel.h"
//最新作业
#import "TheNewWorkListModel.h"
//考勤异常
#import "SYKaoQinYiChangViewController.h"
#import "XGPush.h"

#import "SYNewHomeCollectionViewCell.h"
#import "SYNewHomeMessageView.h"


@interface SYHomeViewController ()<SDCycleScrollViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,HPClassSelectedDateDelegate>
@property (weak, nonatomic) IBOutlet UIView *banderView;
@property (nonatomic, retain) SDCycleScrollView *cycleScrollView;
//轮播图数组
@property (weak, nonatomic) IBOutlet UIView *classView;
@property (weak, nonatomic) IBOutlet UICollectionView *curCollectionView;
@property (nonatomic, strong) NSMutableArray *lunBoTuArray;
@property (nonatomic, strong) NSMutableArray *dataListArr;
@property (weak, nonatomic) IBOutlet UIView *keChengView;//课程view


@property (nonatomic, strong) HPClassView *rightTopView;
///考试
@property (weak, nonatomic) IBOutlet UIView *kaoshiView;//考试
@property (weak, nonatomic) IBOutlet UIView *kaoshiOneView;
@property (weak, nonatomic) IBOutlet UILabel *oneNameLab;
@property (weak, nonatomic) IBOutlet UILabel *oneBanJiLab;
@property (weak, nonatomic) IBOutlet UILabel *oneTimeLab;
@property (weak, nonatomic) IBOutlet UILabel *oneYingJiaoLab;

@property (weak, nonatomic) IBOutlet UIView *kaoshiTwoView;
@property (weak, nonatomic) IBOutlet UILabel *twoName;
@property (weak, nonatomic) IBOutlet UILabel *twoBanjiLab;
@property (weak, nonatomic) IBOutlet UILabel *twoTimeLab;
@property (weak, nonatomic) IBOutlet UILabel *twoYingJiaoLab;


@property (strong, nonatomic) SYNewHomeMessageView *messageView;


//选择最近课程的时间
@property (nonatomic, strong) NSString *dateString;
//即将开始的课程数组
@property (nonatomic, strong) NSMutableArray *beginCourseListArray;
@end

@implementation SYHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setUploadView];
    //信鸽推送
    [self boundNoticeAcount];
    //请求轮播图
    [self getLunBoTuData];
    //请求班级数据
    [self getClassList];
    //请求课程上课信息
    [self theForthcomingCourse];
    //得到老师班级
    [self getMentorClassListRequest];
    //得到考试
    [self zuiXinZuoYeRequest];
    
    [self.curCollectionView headerRefreshBlock:^{
        [self getClassList];
    }];
    
}

- (void)setUploadView {
    self.classView.layer.cornerRadius = 10;
    self.classView.layer.masksToBounds = YES;
    
    self.kaoshiView.layer.cornerRadius = 10;
    self.kaoshiView.layer.masksToBounds = YES;
    
    //添加轮播图
    [self.banderView addSubview:self.cycleScrollView];
    [self.cycleScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.right.equalTo(self.banderView);
    }];
    _lunBoTuArray = [NSMutableArray new];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
         //设置collectionView滚动方向，默认方向为垂直方向
    //     [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    self.curCollectionView.collectionViewLayout = layout;
     _curCollectionView.showsVerticalScrollIndicator = NO ;
     _curCollectionView.showsHorizontalScrollIndicator = NO ;
     //3.注册collectionViewCell，在下面使用处注册
     //4.设置代理
     _curCollectionView.dataSource = self;
     _curCollectionView.delegate = self;
    [self.curCollectionView registerNib:[UINib nibWithNibName:@"SYNewHomeCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"SYNewHomeCollectionViewCell"];
    _dataListArr = [NSMutableArray array];
    
    //课程
    [self.keChengView addSubview:self.rightTopView];
    [self.rightTopView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.right.equalTo(self.keChengView);
    }];
    _beginCourseListArray =  [NSMutableArray array];
    
}
#pragma makr - 请求课程列表
- (void)selectedDate:(NSString *)date{
    [CalendarView initWithDateWithFrame:CGRectMake(self.view.frame.size.width-50, 330, 0, 0) andeSourceView:self.view andDelegate:self andSuccessBlock:^(NSString * _Nonnull date) {
       // NSLog(@"选择的时间 %@",date);
        self->_dateString = date;
        [self theForthcomingCourse];
    }];
}
#pragma makr - 信鸽推送
- (void)boundNoticeAcount{
    NSString *count = [USERDEFAL objectForKey:AcountIDDefalut];
    //解绑账号：
    [[XGPushTokenManager defaultTokenManager] unbindWithIdentifer:count type:XGPushTokenBindTypeAccount];
    //绑定标签：
    [[XGPushTokenManager defaultTokenManager] bindWithIdentifier:count type:XGPushTokenBindTypeAccount];
//    [[XGPushTokenManager defaultTokenManager] setDelegate:self];
}

- (void)xgPushDidBindWithIdentifier:(nonnull NSString *)identifier type:(XGPushTokenBindType)type error:(nullable NSError *)error {
    
}
#pragma mark - 获得老师班级
- (void)getMentorClassListRequest{
    NSDictionary *parama = @{@"name":@"",
                             @"pageIndex":@"0",
                             @"pageSize":@"1000"};
    [SYRequestAPI sy_getClassList:parama success:^(id  _Nonnull responseObject) {
//        NSLog(@"得到老师班级 %@",responseObject);
        NSArray *array = [responseObject objectForKey:@"data"];
        for (NSDictionary *dic in array) {
            TeacherClassListModel *model = [TeacherClassListModel yy_modelWithJSON:dic];
            //[self->_classListArray addObject:model];
        }
 /*
  持久化存储教师班级
  */
        [PublickFunctionObject saveArrayForData:[NSMutableArray arrayWithArray:array] forKey:ClassListOfTeacherDefalut];
    } fail:^(NSError *error) {
        
    }];
}

#pragma mark - 最新作业
- (void)zuiXinZuoYeRequest{
//    if (!_currentMentorClassModel) {
//        _currentMentorClassModel = [TeacherClassListModel new];
//        _currentMentorClassModel.id = @"0";
//    }
    [MBProgressHUD mj_showMessage:nil toView:self.view];
    NSDictionary *parama = @{@"classId":@"0"
                             };
    __weak typeof(self)weakSelf = self;
    [SYRequestAPI sy_getHomeWork:parama success:^(id  _Nonnull responseObject) {
      //  NSLog(@"最新罪业信息 %@",responseObject);
        NSArray *array = [responseObject objectForKey:@"data"];
        if (array.count >=2) {
            [self kaoshiOneViewDict:array.firstObject];
            [self kaoshiTwoViewDict:array[1]];
        } else if (array.count == 1) {
            weakSelf.kaoshiTwoView.hidden = YES;
            [self kaoshiOneViewDict:array.firstObject];
        } else {
            weakSelf.kaoshiOneView.hidden = YES;
            weakSelf.kaoshiTwoView.hidden = YES;
        }
        
        
        [MBProgressHUD mj_hideHUDForView:self.view];
    } fail:^(NSError *error) {
        [MBProgressHUD mj_hideHUDForView:self.view];
    }];
}

- (void)kaoshiOneViewDict:(NSDictionary *)dict {
    self.oneBanJiLab.text = [dict nilObjectForKey:@"className"];
    self.oneNameLab.text = [dict nilObjectForKey:@"lessonName"];
    self.oneTimeLab.text = [dict nilObjectForKey:@"upLoadDate"];
    self.oneYingJiaoLab.text = [NSString stringWithFormat:@"应交：%@人 实交：%@人 ",[dict nilObjectForKey:@"classStudents"],[dict nilObjectForKey:@"submitStudents"]];
}

- (void)kaoshiTwoViewDict:(NSDictionary *)dict {
    self.twoBanjiLab.text = [dict nilObjectForKey:@"className"];
    self.twoName.text = [dict nilObjectForKey:@"lessonName"];
    self.twoTimeLab.text = [dict nilObjectForKey:@"upLoadDate"];
    self.twoYingJiaoLab.text = [NSString stringWithFormat:@"应交：%@人 实交：%@人 ",[dict nilObjectForKey:@"classStudents"],[dict nilObjectForKey:@"submitStudents"]];
}


#pragma mark -
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataListArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    SYNewHomeCollectionViewCell *homeCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SYNewHomeCollectionViewCell" forIndexPath:indexPath];
    NSDictionary *dict = self.dataListArr[indexPath.row];
    homeCell.numberLab.text = [dict nilObjectForKey:@"msgCount"];
    homeCell.className.text = [dict nilObjectForKey:@"name"];
    homeCell.jinduLab.text = [dict nilObjectForKey:@"lessonName"];
    homeCell.shangkeTimeLab.text = [dict nilObjectForKey:@"beginDate"];
   return homeCell;
    
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
//    return UIEdgeInsetsMake(<#CGFloat top#>, <#CGFloat left#>, <#CGFloat bottom#>, <#CGFloat right#>);
    return UIEdgeInsetsMake(10, 0, 10, 10);
}

//设置大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat width = self.curCollectionView.frame.size.width / 4 - 15;
    return CGSizeMake(width, 100);
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString *messageId = self.dataListArr[indexPath.row][@"classId"];
    
    _messageView = [[SYNewHomeMessageView alloc] initWithFrame:CGRectMake(kScreen_WIDTH, 0, CGRectGetWidth(self.view.frame), kScreen_HEIGHT-0)];
    [self.view addSubview:_messageView];
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:kAnimate animations:^{
        weakSelf.messageView.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.frame), kScreen_HEIGHT-0);
        weakSelf.messageView.classId = messageId;
    }];
    
}


#pragma mark - 获取轮播图
- (void)getLunBoTuData{
    __weak typeof(self)weakSelf = self;
    NSDictionary *parama = @{@"position":@"1"};
    [SYRequestAPI sy_getAdvertService:parama success:^(id  _Nonnull responseObject) {
        NSLog(@"得到首页轮播图 %@",responseObject);
        NSArray *dataArray = [responseObject objectForKey:@"data"];
        NSMutableArray *imageUrlArray = [NSMutableArray new];
        for (NSDictionary *dic in dataArray) {
            HomePageLunBoTuModel *model = [HomePageLunBoTuModel yy_modelWithJSON:dic];
            [self->_lunBoTuArray addObject:model];
            [imageUrlArray addObject:model.url];
        }
        if (self->_lunBoTuArray.count>0) {
            weakSelf.cycleScrollView.imageURLStringsGroup = imageUrlArray; // 模拟网络延时情景
        }else{
            weakSelf.cycleScrollView.imageURLStringsGroup =  @[@"u96",@"u100",@"u102"]; // 模拟网络延时情景
        }
        
    } fail:^(NSError *error) {
    }];
}
#pragma mark - 获得即将开始课程
- (void)theForthcomingCourse{
    if (_dateString.length == 0) {
        _dateString = @"";
    }
    [MBProgressHUD mj_showMessage:nil toView:self.view];
    NSDictionary *parama = @{@"currentDate":_dateString};
    [SYRequestAPI sy_getTheForthcomingCourse:parama success:^(id  _Nonnull responseObject) {
        [self->_beginCourseListArray removeAllObjects];
       // NSLog(@"输出获得即将开始课程 %@",responseObject);
        NSArray *array = [responseObject objectForKey:@"data"];
        for (NSDictionary *dic in array) {
            HomeCourseModel *model = [HomeCourseModel yy_modelWithJSON:dic];
            [self->_beginCourseListArray addObject:model];
        }
        self->_rightTopView.dataArray = self->_beginCourseListArray;
        [self->_rightTopView updateView];
        [MBProgressHUD mj_hideHUDForView:self.view];
    } fail:^(NSError *error) {
        [MBProgressHUD mj_hideHUDForView:self.view];
    }];
}
- (void)getClassList {
    __weak typeof(self)weakSelf = self;
    [SYRequestAPI sy_postNoticeReceiveServiceMsgClassInfoSuccess:^(NSArray * _Nonnull dataListArr) {
        [self->_curCollectionView.mj_header endRefreshing];
        [weakSelf.dataListArr removeAllObjects];
        [weakSelf.dataListArr addObjectsFromArray:dataListArr];
        [weakSelf.curCollectionView reloadData];
    } fail:^(NSError *error) {
        [self->_curCollectionView.mj_header endRefreshing];
        
    }];
    
}


#pragma mark - 轮播图回调
//点击了图片的会掉
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index {
    
    
}

#pragma mark - set
- (SDCycleScrollView *)cycleScrollView {
    if (!_cycleScrollView) {
        _cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 210) delegate:self placeholderImage:[UIImage imageNamed:@"lalalala"]];
        _cycleScrollView.pageDotColor = [UIColor whiteColor];
        _cycleScrollView.currentPageDotColor = [UIColor grayColor];
        _cycleScrollView.autoScrollTimeInterval = 2;
        _cycleScrollView.showPageControl = YES;
        _cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
    }
    return _cycleScrollView;
}
- (HPClassView *)rightTopView{
    if (!_rightTopView) {
        HPClassView *view = [[HPClassView alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
        view.delegate  =self;
        view.layer.cornerRadius = 10;
        view.layer.masksToBounds = YES;
        _rightTopView = view;
    }
    return _rightTopView;
}
@end
